package com.yuhong.reggie.controller;

import com.yuhong.reggie.common.R;
import com.yuhong.reggie.entity.User;
import com.yuhong.reggie.service.UserService;
import com.yuhong.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    private UserService userService;
    //注入redisTemplate
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    //处理发送短信的请求
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码"+code);

        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //session.setAttribute(user.getPhone(),code);
        //将验证码存储缓存中,并且设置国企时间5分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        return R.success("发送验证码短信成功");
    }


    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        //接受数据封装到map
        String phone=map.get("phone");//输入手机号
        String userCode= map.get("code");//输入的验证码
        //从session中获取验证码
        //String sessionCode = (String) session.getAttribute(phone);
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);
        //调用业务层进行登录
        User login = userService.login(phone, userCode, sessionCode);
        if (login!=null){
            //登录用户有效,写入用户的idsession (key=user)
            session.setAttribute("user",login.getId());
            //登陆完删除
            //session.removeAttribute(phone);
            //将缓存中的验证码删除
            redisTemplate.delete(phone);
            return R.success(login);
        }
        return R.error("登录失败");
    }
}
